package com.fiidee.blog.controller.common.ueditor;

import com.fiidee.blog.util.Uploader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by 瑱彬 on 2015/5/28.
 */
@Controller
@RequestMapping("/ue")
public class ImageUp {

    @RequestMapping(value = "/upload")
    @ResponseBody
    public String upload(@RequestParam(value = "upfile", required = false) MultipartFile upfile,HttpServletRequest request, HttpServletResponse response){
        try {
            //System.out.println("upfile----->"+new String(upfile.getBytes()));
            Uploader up = new Uploader(request);
            up.setSavePath("upload");
            String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
            up.setAllowFiles(fileType);
            up.setMaxSize(10000); //单位KB
            up.setMultipartFile(upfile);
            up.uploadSigle();

            String callback = request.getParameter("callback");

            String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize() +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";

            result = result.replaceAll( "\\\\", "\\\\" );

            if( callback == null ){
                return result;
            }else{
                return  "<script>"+ callback +"(" + result + ")</script>";
            }
        } catch (Exception e) {
            return "<script>alert('上传错误')</script>";
        }
    }
}
